<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <title>贪吃蛇游戏</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f0f0f0;
            font-family: Arial, sans-serif;
        }

        #gameCanvas {
            border: 2px solid #333;
            background-color: #fff;
            margin: 20px;
        }

        #score {
            font-size: 24px;
            margin-bottom: 10px;
        }

        #startBtn {
            padding: 10px 20px;
            font-size: 18px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-bottom: 20px;
        }

        #startBtn:hover {
            background-color: #45a049;
        }
    </style>
</head>

<body>
    <h1>贪吃蛇游戏</h1>
    <div id="score">分数: 0</div>
    <button id="startBtn">开始游戏</button>
    <canvas id="gameCanvas" width="400" height="400"></canvas>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const startBtn = document.getElementById('startBtn');

        const gridSize = 20;
        const tileCount = canvas.width / gridSize;

        let snake = [];
        let food = {};
        let dx = gridSize;
        let dy = 0;
        let score = 0;
        let gameInterval;
        let gameStarted = false;

        function initGame() {
            snake = [
                { x: 5 * gridSize, y: 5 * gridSize }
            ];
            generateFood();
            score = 0;
            scoreElement.textContent = `分数: ${score}`;
            dx = gridSize;
            dy = 0;
        }

        function generateFood() {
            food = {
                x: Math.floor(Math.random() * tileCount) * gridSize,
                y: Math.floor(Math.random() * tileCount) * gridSize
            };
            // 确保食物不会生成在蛇身上
            for (let segment of snake) {
                if (segment.x === food.x && segment.y === food.y) {
                    generateFood();
                    break;
                }
            }
        }

        function drawGame() {
            // 清空画布
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制蛇
            ctx.fillStyle = 'green';
            for (let segment of snake) {
                ctx.fillRect(segment.x, segment.y, gridSize - 2, gridSize - 2);
            }

            // 绘制食物
            ctx.fillStyle = 'red';
            ctx.fillRect(food.x, food.y, gridSize - 2, gridSize - 2);
        }

        function moveSnake() {
            const head = { x: snake[0].x + dx, y: snake[0].y + dy };

            // 检查是否撞墙
            if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
                gameOver();
                return;
            }

            // 检查是否撞到自己
            for (let segment of snake) {
                if (head.x === segment.x && head.y === segment.y) {
                    gameOver();
                    return;
                }
            }

            snake.unshift(head);

            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                score += 10;
                scoreElement.textContent = `分数: ${score}`;
                generateFood();
            } else {
                snake.pop();
            }
        }

        function gameOver() {
            clearInterval(gameInterval);
            gameStarted = false;
            startBtn.textContent = '重新开始';
            alert(`游戏结束！你的得分是: ${score}`);
        }

        function gameLoop() {
            moveSnake();
            drawGame();
        }

        startBtn.addEventListener('click', () => {
            if (!gameStarted) {
                initGame();
                gameStarted = true;
                startBtn.textContent = '游戏中...';
                gameInterval = setInterval(gameLoop, 150);
            }
        });

        document.addEventListener('keydown', (event) => {
            if (!gameStarted) return;

            switch (event.key) {
                case 'ArrowUp':
                    if (dy === 0) {
                        dx = 0;
                        dy = -gridSize;
                    }
                    break;
                case 'ArrowDown':
                    if (dy === 0) {
                        dx = 0;
                        dy = gridSize;
                    }
                    break;
                case 'ArrowLeft':
                    if (dx === 0) {
                        dx = -gridSize;
                        dy = 0;
                    }
                    break;
                case 'ArrowRight':
                    if (dx === 0) {
                        dx = gridSize;
                        dy = 0;
                    }
                    break;
            }
        });
    </script>
</body>

</html>